import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface AppConfig {
  title: string
  version: string
  apiBaseUrl: string
  enableDebug: boolean
}

export const useAppStore = defineStore('app', () => {
  // 状态
  const loading = ref(false)
  const sidebarCollapsed = ref(false)
  const config = ref<AppConfig>({
    title: 'CodeWin AI角色扮演平台',
    version: '1.0.0',
    apiBaseUrl: import.meta.env.VITE_API_BASE_URL || '/api',
    enableDebug: import.meta.env.DEV
  })

  const breadcrumbs = ref<Array<{ name: string; path?: string }>>([])
  const pageTitle = ref('')

  // 计算属性
  const isLoading = computed(() => loading.value)
  const appTitle = computed(() => config.value.title)

  // 方法
  function setLoading(state: boolean) {
    loading.value = state
  }

  function toggleSidebar() {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }

  function setSidebarCollapsed(collapsed: boolean) {
    sidebarCollapsed.value = collapsed
  }

  function setBreadcrumbs(items: Array<{ name: string; path?: string }>) {
    breadcrumbs.value = items
  }

  function setPageTitle(title: string) {
    pageTitle.value = title
    document.title = title ? `${title} - ${config.value.title}` : config.value.title
  }

  function updateConfig(updates: Partial<AppConfig>) {
    config.value = { ...config.value, ...updates }
  }

  function initApp() {
    // 设置初始页面标题
    document.title = config.value.title
  }

  return {
    loading,
    sidebarCollapsed,
    config,
    breadcrumbs,
    pageTitle,
    isLoading,
    appTitle,
    setLoading,
    toggleSidebar,
    setSidebarCollapsed,
    setBreadcrumbs,
    setPageTitle,
    updateConfig,
    initApp
  }
}, {
  persist: {
    key: 'app-store',
    storage: localStorage,
    pick: ['sidebarCollapsed'] // 只持久化侧边栏状态
  }
})